import PureUserRole from '../components/user-role';
import * as RoleAction from 'actions/role';
import { getFetchStatus } from 'actions/util';
import * as ReactRedux from 'react-redux';
import * as React from 'react';

const mapStateToProps = (state) => {
  return {
    fetchRoles: getFetchStatus(state, RoleAction.listByUserId),
    deleteFetch: getFetchStatus(state, RoleAction.deleteById),
    createFetch: getFetchStatus(state, RoleAction.create),
    roles: state.rolesByUserId
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    initFetch: (userId) => {
      dispatch(RoleAction.listByUserId(userId));
    },
    onRoleDelete(id, roleId) {
      dispatch(RoleAction.deleteById(id))
        .then(()=> {
          dispatch(RoleAction.listByUserId(roleId));
        });
    },
    onSAEnable(userId){
      const role = {
        type: 'SYS_ADMIN',
        userId: userId
      }
      dispatch(RoleAction.create(role))
        .then(()=> {
          dispatch(RoleAction.listByUserId(userId));
        });
    },
    onSADisable(saRoleId, userId){
      dispatch(RoleAction.deleteById(saRoleId))
        .then(()=> {
          dispatch(RoleAction.listByUserId(userId));
        });
    },
    onCreateRole(role){
      return dispatch(RoleAction.create(role))
        .then(()=> {
          dispatch(RoleAction.listByUserId(role.userId));
        });
    }
  };
};

class UserRole extends React.Component {
  componentDidMount() {
    this.props.initFetch(this.props.user.id);
  }

  render() {
    return <PureUserRole {...this.props}/>;
  }
}

export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(UserRole);
